<template>
  <!--Modal修改密码-->
  <a-modal
    title="修改密码"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
      :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
    >
      <a-row :gutter="24">
        <a-col
          :md="24"
          :sm="24"
        >
          <a-form-model-item
            label="输入原密码"
            prop="password"
          >
            <a-input
              v-model.trim="form.password"
              class="disabled-pwd"
              autocomplete="new-password"
              type="text"
              placeholder="请输入原密码"
            >
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(0, 0, 0, 0.25)"
              />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="24"
          :sm="24"
        >
          <a-form-model-item
            label="输入新密码"
            prop="newPassword"
          >
            <a-input
              v-model.trim="form.newPassword"
              class="disabled-pwd"
              autocomplete="new-password"
              type="text"
              onkeyup="(value = value.replace(/[\u4E00-\u9FA5]/g, ''))"
              placeholder="请输入新密码"
            >
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(0, 0, 0, 0.25)"
              />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="24"
          :sm="24"
        >
          <a-form-model-item
            label="确认新密码"
            prop="newPasswordAgain"
          >
            <a-input
              v-model.trim="form.newPasswordAgain"
              class="disabled-pwd"
              autocomplete="new-password"
              type="text"
              onkeyup="(value = value.replace(/[\u4E00-\u9FA5]/g, ''))"
              placeholder="请确认新密码"
            >
              <a-icon
                slot="prefix"
                type="lock"
                style="color: rgba(0, 0, 0, 0.25)"
              />
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>

<script>
import { updataUserManagePsw } from '@/api/system/system'
import { mapActions } from 'vuex'
import { clientId, clientSecret, PublicKey } from '@/config'
import { login } from '@/api/login'
import { encryptFromText } from '@/tool/sm.js'
import Vue from 'vue'
export default {
  name: 'ModalPsw',
  props: {
    visible: {
      value: false,
      type: Boolean
    },
    // 修改密码的参数，eg: { userName: string, passWord: string }
    queryArg: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      const regex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}')
      // const reg = /([a-zA-Z0-9!@#$%^&*()_?<>{}]){6,18}/
      if (!regex.test(value)) {
        // callback(new Error('请输入6到16位密码'))
        callback(new Error('请输入8到30位密码，密码中必须包含大写小写字母、数字、特殊字符'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
        newPasswordAgain: [{ required: true, validator: validatePass, trigger: 'blur' }]
      },
      confirmLoading: false,
      form: {
        password: '',
        newPassword: '',
        newPasswordAgain: ''
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val && this.queryArg.passWord) {
          this.form = {
            ...this.form,
            password: this.queryArg.passWord
          }
        }
      }
    }
  },
  created() {},
  methods: {
    doSm3AndSm2Encrypt(sourceStr) {
      // 密码加密
      /* eslint-disable */
      const sm2Utils = new Sm2Utils()
      const public_key = PublicKey
      const sm3_random_plain = Sm3Utils.encryptFromText(sourceStr) + '|' + sm2Utils.randomWord(8) + '|' + sourceStr
      const sm3_sm2_plain = sm2Utils.encryptFromText(public_key, sm3_random_plain)
      return '{crypto}' + sm3_sm2_plain
      /* eslint-enable */
    },

    /**
     *@desc 修改密码
     *@param {}
     */
    handleOk(e) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.newPassword != this.form.newPasswordAgain) {
            this.$message.warning('两次新密码不一致')
            return
          }
          try {
            const userName = this.queryArg.userName || JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
            const params = {
              // userId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
              username: userName,
              sign: encryptFromText(userName),
              pscode: this.doSm3AndSm2Encrypt(this.form.password),
              newPscode: this.doSm3AndSm2Encrypt(this.form.newPassword),
              qq: window.btoa(this.form.newPassword) // 修改密码时传给后端存储下来
            }
            this.confirmLoading = true
            updataUserManagePsw(params)
              .then((res) => {
                if (res.status === 200) {
                  //密码更改成功
                  this.handleCancel()
                  this.confirmLoading = false
                  this.$message.success('修改成功')
                  // 登录页面修改密码就直接返回，不用再次退出登录
                  if (this.queryArg.passWord) {
                    return
                  }
                  Vue.getAcloudProvider().logout()
                }
              })
              .catch((err) => {
                //密码更改失败
                console.log(err)
                // this.$message.warning(err.message)
                this.confirmLoading = false
              })
          } catch (e) {
            console.error(e)
            this.confirmLoading = false
          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
          this.confirmLoading = false
          return false
        }
      })
    },
    /**
     *@desc  table列表密码重置取消
     *@param {}
     */
    handleCancel(e) {
      this.$refs.ruleForm.resetFields()
      this.$emit('handleCancel', false)
    }
  }
}
</script>

<style>
@font-face {
  font-family: 'password';
  src: url('~@/assets/font/passwordEntry.ttf');
}
.disabled-pwd {
  text-security: disc;
  -webkit-text-security: disc;
  font-family: 'password';
}
.modalForm .ant-form-item .ant-form-item-control-wrapper {
  width: 90%;
  padding-left: 10%;
}
</style>
